#!/bin/sh

die() { echo "$1" >&2; exit 1; }

PRUDYNT_CONFIG_FILE="/etc/prudynt.json"

show_help() {
	echo "Thingino Diagnostics Script
Generate diagnostics log shared via tb.thingino.com

Usage: $0 [-l [path]]
Where:
	-l	Save the log to a local file instead of uploading.
		Optional: specify a custom path (default: /tmp)
"
	exit 0
}

header() {
	local len=$((73 - ${#1}))
	echo -en "\n\n===[ $1 ]"
	for i in $(seq 1 $len); do echo -n "="; done
	echo -e "\n\n"
}

infocat() {
	[ -f "$1" ] || return
	[ -n "$2" ] && header "$2"
	cat $1
}

inforun() {
	tmp=$(mktemp) || exit 1
	eval "$1" >"$tmp" && [ -s "$tmp" ] && { [ -n "$2" ] && header "$2"; cat "$tmp"; }
	rm -f "$tmp"
}

local_file=""
output_path="/tmp"
while getopts ":lh" opt; do
	case $opt in
		l)
			local_file="yes"
			shift $((OPTIND-1))
			output_path="${1:-/tmp}"
			[ -d "$output_path" ] || die "Error: Directory $output_path does not exist"
			[ -w "$output_path" ] || die "Error: Directory $output_path is not writable"
			;;
		h)
			show_help
			;;
		\?)
			echo "Invalid option: -$OPTARG"
			show_help
			;;
	esac
done

if [ -t 0 ]; then
	echo "Thingino Diagnostics"
	[ -z "$local_file" ] && echo "This script requires network access."
	echo "
This script generates a log file for sharing with developers for diagnostic issues.
The log may contain sensitive information, please review it before sharing the link!
We use a self-hosted fiche server to share the log. Files are stored for 1 week.
"
	read -p "Do you wish to proceed? (yes/no): " response
	[ "yes" = "$response" ] || die "Operation aborted by the user."
fi

if [ -n "$local_file" ]; then
	output_file="$output_path/thingino-diag-$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 4).log"
else
	output_file=$(mktemp)
fi

{
	inforun "date"
	inforun "uptime"
	inforun "uname -a"
	inforun "grep -a \"Thingino\" /dev/mtd0"
	infocat "/etc/os-release" "THINGINO"
	inforun "soc;soc -w" "SOC"

	header "ENV"
	fw_printenv | awk -F'=' '{if (/ethaddr|gatewayip|ipaddr|root_pw_hash|pwbackup|serverip|ssh_authorized_keys|sshkey|wlan_ssid|wlan_mac|wlan_pass|wg_dns|wg_address|wg_endpoint|wg_peerpub|wg_peerpsk|wg_allowed/) print $1 "=REDACTED"; else print}' | sort

	infocat "/proc/cmdline" "CMDLINE"
	inforun "gpio list" "GPIO"
	inforun "df -h" "DF"
	inforun "ipcs" "IPC"
	inforun "find /sys -path '*mmc*vendor' -type f -exec sh -c 'echo \"Vendor: \$1\"; cat \"\$1\"; dev=\"\${1/vendor/device}\"; [ -f \"\$dev\" ] && { echo \"Device: \$dev\"; cat \"\$dev\"; }' _ {} \;" "MMC"

	inforun "lsmod" "KMOD"
	header "KMOD-2"
	for file in /etc/modules.d/*; do
		echo "== $file =="
		cat "$file"
	done

	[ -d /sys/bus/usb/devices/ ] && inforun "lsusb" "USB"

	inforun "free -h" "MEMORY"
	inforun "mount" "MOUNT"

	infocat "/proc/jz/clock/clocks" "CLOCKS"
	infocat "/proc/jz/isp/isp-fs" "isp-fs"
	infocat "/proc/jz/isp/isp-m0" "isp-m0"
	infocat "/proc/jz/isp/isp_info" "isp_info"
	infocat "/tmp/continuous_mem_info" "libimp meminfo"

	inforun "sensor -a" "sensor"

	inforun "ps" "PS"
	inforun "lsof" "LSOF"
	inforun "dmesg" "DMESG"
	inforun "logcat -t" "LOGCAT"
	inforun "logread" "SYSLOG"

	header "streamer"
	sed 's/"password": "[^"]*"/"password": "REDACTED"/g' $PRUDYNT_CONFIG_FILE

	infocat "/etc/cron/crontabs/root" "crontab"
} > "$output_file"

sed -E -i 's/(openRTSP -V -u) (\w*) (\w*) (.*)$/\1 REDACTED REDACTED \4/' $output_file

if [ -z "$local_file" ]; then
	url=$(send2termbin < $output_file)
	rm -f "$output_file"

	[ -z "$url" ] && die "\nThere was an error."

	echo "Your diagnostics log link:"
	echo "$url"
else
	echo "Diagnostics log saved locally at $output_file"
fi

exit 0
